package com.langrensha.langrensha.store;

import com.langrensha.langrensha.entity.Room;
import com.langrensha.langrensha.entity.UserInfo;
import com.langrensha.langrensha.entity.UserStatusEnum;
import io.netty.channel.Channel;

import java.util.*;

public class UserStore {

    private static final Map<String, UserInfo> NAME_USERINFO = new HashMap<>();
    private static final Map<String, UserInfo> SEAT_USERINFO = new HashMap<>();
    private static final Map<Channel, UserInfo> CHANNEL_USERINFO = new HashMap<>();
    public static final Set<String> USER_ALIAS = new HashSet<>();

    public static UserInfo getByName(String hostId, String key) {
        return NAME_USERINFO.get(hostId + key);
    }

    public static UserInfo getByChannel(Channel key) {
        return CHANNEL_USERINFO.get(key);
    }

    public static UserInfo getBySeatId(String hostId, String key) {

        return SEAT_USERINFO.get(hostId + key);
    }

    public static boolean addUserAlias(String name) {
        return USER_ALIAS.add(name);
    }

    public static void save(UserInfo userInfo) {

        if (userInfo.getName() != null) {
            NAME_USERINFO.put(userInfo.getHostId() + userInfo.getName(), userInfo);
        }
        if (userInfo.getSeatId() != null) {
            SEAT_USERINFO.put(userInfo.getHostId() + userInfo.getSeatId(), userInfo);
        }
        if (userInfo.getChannel() != null) {
            CHANNEL_USERINFO.put(userInfo.getChannel(), userInfo);
        }
    }
    public static void addSeatUserINFO(String hostId,String seatId,UserInfo u) {
        SEAT_USERINFO.put(hostId + seatId, u);
    }

    public static void removeSeatInfo(String hostId, String seatId) {
        SEAT_USERINFO.remove(hostId + seatId);
    }

    /**
     * socket离线
     *
     * @param incoming 当前离线的socket
     */
    public static void handChannelRemove(Channel incoming) {
        UserInfo u = CHANNEL_USERINFO.get(incoming);
        u.setStatus(UserStatusEnum.SUSPENDED);
        // 游戏发牌之后
        RoomStore.removeChannel(u.getHostId(),incoming);
        u.setChannel(null);
        // 游戏发牌之前,清空座位信息。
    }

    /**
     * socket离线
     *
     * @param u 离线的用户
     */
    public static void handChannelRemove(UserInfo u) {
        CHANNEL_USERINFO.remove(u.getChannel());
        u.setStatus(UserStatusEnum.SUSPENDED);
        // 游戏发牌之后
        RoomStore.removeChannel(u.getHostId(),u.getChannel());
        u.setChannel(null);
        // 游戏发牌之前,清空座位信息。
    }

    public static void addImageInfo(UserInfo u) {
        Room room = RoomStore.getRoom(u.getHostId());
        List<String> list = room.getImages();
        int num = new Random().nextInt(list.size());
        String image = list.remove(num);
        u.setImg(image);
    }
}
